//
//  RegistViewCtrlOne.m
//  DDHuilai
//
//  Created by nianfangge on 16/3/28.
//  Copyright © 2016年 Admin. All rights reserved.
//

#import "RegistViewCtrlOne.h"
#import "NetRequest+user.h"
#import "CreatePassWordViewCtrl.h"

@interface RegistViewCtrlOne ()
{
    UIView *agreementView;
}

@property (nonatomic,weak) IBOutlet UITextField *phoneTextField;

@property (nonatomic,weak) IBOutlet UITextField *vertifyTextField ;

@property (nonatomic,weak) IBOutlet UIButton *vertifyButton;

@property (nonatomic,weak) IBOutlet UIButton *signUpBtn;

@property (nonatomic,weak) IBOutlet UIView *topDivideLine;

@property (nonatomic,weak) IBOutlet UIView *bottomDivideLine;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *topInterval;


- (IBAction)signUp:(id)sender;

@property (nonatomic,strong)NSString *emailAddress;

@property (nonatomic,strong)NSString *verifyCode;

- (void)reloadVerifyBtnStatus;
- (IBAction)goBack:(id)sender;

@end

@implementation RegistViewCtrlOne

#pragma mark ----生命周期方法-------

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"注册";
    [self navBarLeftButtonImage:@"back"];
    setCornerRadius(self.signUpBtn, 20);
    
    self.phoneTextField.text = @"877340657@qq.com";
    self.vertifyTextField.text = @"asasa";
    self.vertifyButton.layer.borderWidth = 1;
    self.vertifyButton.layer.cornerRadius = 3;
    self.vertifyButton.layer.borderColor = [UIColor clearColor].CGColor;
    [self.vertifyButton setBackgroundColor:KLoginOrangeColor];
    self.signUpBtn.enabled = NO;
    [self.signUpBtn setBackgroundColor:KLoginGrayColor];
    [self.vertifyButton addTarget:self action:@selector(vertificationCodeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    [self addNotifications];
    
    [self reloadVerifyBtnStatus];
    [self reloadSigninBtnStatus];

}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [_timer invalidate];
    _timer = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - 通知
- (void)addNotifications {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillChangeFrame:) name:UIKeyboardWillChangeFrameNotification object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardDidChangeFrame:) name:UIKeyboardDidChangeFrameNotification object:nil];    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:_vertifyTextField];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(textFiledEditChanged:)
                                                name:@"UITextFieldTextDidChangeNotification"
                                              object:_phoneTextField];

}


#pragma mark ---- Private Method
- (void)reloadSigninBtnStatus {
    if (![self.verifyCode isEqualToString:@""] && ![self.emailAddress isEqualToString:@""])
    {
        self.signUpBtn.enabled = YES;
        self.signUpBtn.backgroundColor = KLoginOrangeColor;
        
    }else{
        self.signUpBtn.enabled = NO;
        self.signUpBtn.backgroundColor = KLoginGrayColor;
    }
}

- (void)reloadVerifyBtnStatus {
    //可能要先这样写,?////
    BOOL vaild = isVailedEmail(self.emailAddress);
    if (isVailedEmail(self.phoneTextField.text))
    {
        self.vertifyButton.enabled = YES;
        [self.vertifyButton setBackgroundColor:KLoginOrangeColor];
    }else {
        self.vertifyButton.enabled = NO;
        [self.vertifyButton setBackgroundColor:KLoginGrayColor];
    }
}

#pragma mark --------UItextField的委托和通知----------
- (void)textFiledEditChanged:(UITextField *)textfield
{
    
    [self reloadSigninBtnStatus];
    
  
    if(!m_VertifyControlFlag)
    {
        [self reloadVerifyBtnStatus];
    }

}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if (490 > kScreenHeight)
    {
        NSLog(@"frame =%@ bounds=%@",NSStringFromCGRect(self.view.frame),NSStringFromCGRect(self.view.bounds));
        [UIView animateWithDuration:0.3 animations:^{
            self.topInterval.constant = 20;
        }];
    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField;              // called when 'return' key pressed. return NO to ignore.
{
    [self.view endEditing:YES];
    return  YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField == self.phoneTextField) {
        if (isVailedEmail(textField.text)) {
            
            
        }
    }
}


// 验证码网络请求参数
- (NSDictionary *)loadRequestParamsWithPhone:(NSString *)phone
{
    NSDictionary *dic = @{
                          @"mobile"  : phone,
                          @"type" : @"L",
                          @"isVoice" : @"false"
                          };
    
    return dic;
}



#pragma mark -验证码相关方法
- (void)setVerify
{
    m_VertifyControlFlag = YES;
    _timeCount = 60;
    NSString *str = [NSString stringWithFormat:@"%d秒后重发", (int)_timeCount];
    [self.vertifyButton setTitle:str forState:UIControlStateDisabled];
    if (IOS7 && (!IOS8))
    {
        [self.vertifyButton setTitle:str forState:UIControlStateDisabled];
    }
    self.vertifyButton.enabled = NO;
    self.vertifyButton.backgroundColor =KLoginGrayColor;
    _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(countDownDurationEvent:) userInfo:nil repeats:YES];
}

- (void)countDownDurationEvent:(id)sender
{
    if (_timeCount != 0) {
        _timeCount --;
        NSString *str = [NSString stringWithFormat:@"%d秒后重发", (int)_timeCount];
        [self.vertifyButton setTitle:str forState:UIControlStateDisabled];
        if (IOS7 && (!IOS8))
        {
            [self.vertifyButton setTitle:str forState:UIControlStateDisabled];
        }
        self.vertifyButton.backgroundColor =KLoginGrayColor;
    }else{
        [_timer invalidate];
        self.vertifyButton.enabled = YES;
        m_VertifyControlFlag = NO;
        [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        if (IOS7 && (!IOS8))
        {
            [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
        }
        [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
        _vertifyButton.backgroundColor = KLoginOrangeColor;
    }
}

#pragma mark -新建密码界面
- (void)pushToNewPassWordViewCtrl
{
    [self.vertifyTextField resignFirstResponder];
    CreatePassWordViewCtrl *passwordCtrl = [[CreatePassWordViewCtrl alloc] initWithNibName:@"CreatePassWordViewCtrl" bundle:nil];
    passwordCtrl.eamilAddress = self.emailAddress;
    [self.navigationController pushViewController:passwordCtrl animated:YES];
}

#pragma mark - 请求网络

// 设置网络请求参数
- (NSDictionary *)loadRequestParamsWithPhone:(NSString *)phone AndVertifyCode:(NSString *)vertifyCode
{
    NSDictionary *dic = @{
                          @"mobile" : phone,
                          @"verifyCode" : vertifyCode
                          };
    
    return dic;
}


#pragma mark - 通知事件
-(void)keyboardWillChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
    CGFloat keheight = keyboardF.size.height;
    CGFloat keyY = keyboardF.origin.y;
    
    if (self.signUpBtn.bottom > keyY) {
        [UIView animateWithDuration:duration animations:^{
            self.topInterval.constant = keyY - self.logoTopToSignBtnBot;
            [self.view layoutIfNeeded];
        }];
    }
    if (keyY >= kScreenHeight && self.topInterval.constant != 200) {
        [UIView animateWithDuration:duration animations:^{
            self.topInterval.constant = 200;
            [self.view layoutIfNeeded];
        }];
    }
}

-(void)keyboardDidChangeFrame:(NSNotification *)notification{
    
    NSDictionary *userInfo = notification.userInfo;
    // 动画的持续时间
    //    double duration = [userInfo[UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    // 键盘的frame
    CGRect keyboardF = [userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    NSLog(@"%@",NSStringFromCGRect(keyboardF));
    
    
}

#pragma mark - action事件
- (void)leftButtonclickEvent:(id)sender
{
    if (self.dismissBlock) {
        self.dismissBlock();
    }
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

- (IBAction)signUp:(id)sender {
    WeakSelf(ws);
    [self.view endEditing:YES];
    [SVProgressHUD showWithStatus:@"注册中..."];
    NSDictionary *params = [self loadRequestParamsWithPhone:self.emailAddress AndVertifyCode:self.verifyCode];
    NSURLSessionDataTask *dataTask = [[NetRequest sharedInstance] registDictionary:params success:^(UserMode *user) {
        user.loginName = ws.emailAddress;
        [SVProgressHUD dismiss];
        
        [_timer invalidate];
        _timer = nil;
        _timeCount = 0;
        ws.vertifyButton.enabled = YES;
        m_VertifyControlFlag = NO;
        [ws.vertifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
        [ws.vertifyButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
        _vertifyButton.backgroundColor = KLoginOrangeColor;
        ws.vertifyTextField.text = nil;
        //保存邮箱
        [kUserDefaults setObject:self.emailAddress forKey:LOGIN_EmailAddress];
        [ws pushToNewPassWordViewCtrl];
        
    } fail:^(RequestError *error) {
        [SVProgressHUD dismissWithError:error.errorMsg];
        //暂时失败里也写这个流程,,测试用啊
        [kUserDefaults setObject:self.emailAddress forKey:LOGIN_EmailAddress];
        [ws pushToNewPassWordViewCtrl];
    }];
    
    [self addSessionDataTask:dataTask];
    
}


- (IBAction)goBack:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}


- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

// 获取验证码
- (void)vertificationCodeButtonClick:(UIButton *)button
{
    NSString *phontext = [_phoneTextField.text  stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if (isVailedEmail(phontext))
    {
        [self setVerify];
        button.backgroundColor  = KLoginGrayColor;
        button.enabled = NO;
        
        NSDictionary *params = [self loadRequestParamsWithPhone:phontext];
        
        NSURLSessionDataTask *dataTask = [[NetRequest sharedInstance] getVerificationCodeDictionary:params success:^(BOOL isSucess) {
            
            if (isSucess) {
                [SVProgressHUD showSuccessWithStatus:@"获取验证码成功"];
                self.vertifyTextField.text = nil;
            }
            
        } fail:^(RequestError *error) {
            
            if ([error.errorCode isEqualToString:@"30000025"])
            {
                [SVProgressHUD showErrorWithStatus:@"邮箱号已注册！"];
                [_timer invalidate];
                _timer = nil;
                _timeCount = 60;
                m_VertifyControlFlag = NO;
                self.vertifyButton.enabled = YES;
                [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
                _vertifyButton.backgroundColor = KNormalOrangeColor;
            }
            else if (![error.errorCode isEqualToString:@"0"])
            {
                [SVProgressHUD showErrorWithStatus:@"获取验证码失败"];
                [_timer invalidate];
                _timer = nil;
                _timeCount = 60;
                m_VertifyControlFlag = NO;
                self.vertifyButton.enabled = YES;
                [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateNormal];
                [self.vertifyButton setTitle:@"获取验证码" forState:UIControlStateDisabled];
                _vertifyButton.backgroundColor = KNormalOrangeColor;
            }
            
        }];
        
        [self addSessionDataTask:dataTask];
        
    }
    else{
        [SVProgressHUD showErrorWithStatus:@"请输入正确的手机号码"];
    }
    
}

#pragma mark -getter
- (NSString *)emailAddress {
    NSString *phone = [self.phoneTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return phone;
}

- (NSString *)verifyCode {
    NSString *vertify= [self.vertifyTextField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    return vertify;
}

- (CGFloat)logoTopToSignBtnBot {
    return self.signUpBtn.bottom - self.phoneTextField.top;
}

@end
